#!/usr/bin/env python
# coding=utf-8
import psutil
from os import error, system, path
import configparser
import logging
import webbrowser
from shutil import copyfile
import platform

run_log = './Runs.txt'
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s :%(levelname)s :%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
fhlr = logging.FileHandler(run_log)  # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(fhlr)


# 访问网站
def ff(url):
    webbrowser.open(url)


# 配置文件模板
config_file = str('''
[Intranet]
IP=172.31.0.127
GATEWAY=172.31.0.254
NETMASK=255.255.255.0
DNS1=172.31.0.254
DNS2=119.29.29.29



[Extranet]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114

[customize1]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114

[customize2]
IP=10.0.9.123
GATEWAY=10.0.9.254
NETMASK=255.255.255.0
DNS1=119.29.29.29
DNS2=114.114.114.114
''')


def get_ipaddr(ifname):
    """
    传入一个网卡名，然后就可以获取到这个网卡的IP地址
    """
    dic = psutil.net_if_addrs()
    ipv4_list = []
    for adapter in dic:
        if str(adapter) == str(ifname):
            snicList = dic[adapter]
            for snic in snicList:
                if snic.family.name == 'AF_INET':
                    ipv4 = snic.address
                    if ipv4 != '127.0.0.1':
                        ipv4_list.append(ipv4)
                        if len(ipv4_list) >= 1:
                            return ipv4_list[0]
                        else:
                            return 'None'


# 开始配置
def config(card, ip, netmask, gateway, dns1, dns2):
    dhcp_cmd = "netsh interface ipv4 set address name=\"" + card + "\" source=dhcp"
    ip_cmd = "netsh interface ip set address name=\"" + card + "\" source=static address=" + ip + " mask=" + netmask + " gateway=" + gateway
    dns_cmd = "netsh interface ipv4 set dnsservers name=\"" + card + "\" source=static address=" + dns1 + " register=primary validate=no"
    dns2_cmd = "netsh interface ipv4 add dnsservers  name=\"" + card + "\" " + dns2 + " index=2 validate=no"
    try:
        print("正在对[ %s ]清除配置..." % card)
        logger.info("正在对[ %s ]清除配置-->[ %s ]" % (card, dhcp_cmd))
        system(dhcp_cmd)

        print("正在对[ %s ]设置IP--->[ %s ]" % (card, ip))
        logger.info("正在对[ %s ]设置IP--->[ %s ]" % (card, ip_cmd))
        system(ip_cmd)

        print("正在对[ %s ]设置DNS1-->[ %s ]" % (card, dns1))
        logger.info("正在对[ %s ]设置DNS1-->[ %s ]" % (card, dns_cmd))
        system(dns_cmd)

        print("正在对[ %s ]设置DNS2-->[ %s ]" % (card, dns2))
        logger.info("正在对[ %s ]设置DNS1-->[ %s ]" % (card, dns2_cmd))
        system(dns2_cmd)


    except error:
        print("请检查本机是否存在此IP[ %s ]" % ip)
    get_netcard()


# 获取配置文件内容
def get_config(file, mode, card_name, ip_list, ip_info):
    """
    file #选择一个配置文件
    mode  #选择一个section(部分)
    card_name #网卡名
    """
    if path.isfile(file):
        net_config = configparser.ConfigParser()
        net_config.read(file, encoding='utf8')
        IP = net_config.get(mode, "IP")
        GATEWAY = net_config.get(mode, "GATEWAY")
        NETMASK = net_config.get(mode, "NETMASK")
        DNS1 = net_config.get(mode, "DNS1")
        DNS2 = net_config.get(mode, "DNS2")

        for i in ip_list:
            if i == IP:
                dev = ip_info[i]
                ii = "本机[ %s ]已存在相同的IP--->[ %s ]" % (dev, IP)
                print(ii)
                logger.info(ii)
            else:
                config(card=card_name, ip=IP, netmask=NETMASK, gateway=GATEWAY, dns1=DNS1, dns2=DNS2)
    else:
        ii = ("文件[ %s ]不存在,已新建该配置文件，请按需修改后再执行" % file)
        print(ii)
        logger.error(ii)
        rw_file = open(file, 'w', encoding='utf8')
        rw_file.write(config_file)
        rw_file.close()
        print(config_file)
        print('请根据需求修改以上内容--->[ %s ]' % file)
        d = input('按任意键终止程序')


##获取本机网卡列表
def get_netcard():
    network_info = {'IP': 'equipment'}
    net_mode = ''
    netcard_info = []
    ip_list = ''
    ip_list = []
    info = psutil.net_if_addrs()

    # k就是网卡名称
    for k, v in info.items():
        for item in v:
            if item[0] == 2 and not item[1] == '127.0.0.1':
                netcard_info.append(k)
                ip_list.append(item[1])
                dic = {item[1]: k}
                network_info.update(dic)

    i = 0
    net_lists = []
    net_list = []
    for k in netcard_info:
        i = i + 1
        net_list.append("[ " + str(i) + " ]" + k)
        net_lists.append(k)
    ii = ('一共有[ %s ]个网卡' % i)
    logger.info(ii)
    for s in net_list:
        print(s)
    print('[q]退出程序\n[f]关注作者今日头条\n[QQ]加入QQ群')
    # 设置第一个网卡为默认网卡(0是第一，1是第二)
    default_card = net_lists[0]

    net_name = ''
    net_card = input('请选择一个网卡进行操作,默认---> ([1] %s )\n' % default_card)
    for use in range(1, i):
        if str(net_card) == str(use):
            i = int(use) - 1
            net_name = net_lists[i]
    if net_card:
        if str(net_card) == 'q':
            ii = ('感谢使用\nBy:  坐公交也用券@(今日头条,CSDN,博客园)')
            print(ii)
            logger(ii)
        elif str(net_card) == 'f':
            ff(url='https://www.toutiao.com/c/user/token/MS4wLjABAAAAhkfCgYOJBcLeeCmKBkqlgADR-D_woot1lAXGJFnkEnE/')
            exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
        elif str(net_card) == 'QQ':
            ff(url='https://jq.qq.com/?_wv=1027&k=9GhKf7W5')
            exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
        else:
            exit('输入错误，程序终止')
        ii = ('已选择[ %s ]' % net_name)
        print(ii)
        logger.info(ii)
    else:
        net_name = default_card
        print('设置默认网卡-->[ %s ]' % net_name)
    select_net = input('''请选择需要设置的模式/IP
[1]设置内网---->[ Intranet ]
[2]设置外网---->[ Extranet ]
[3]使用自定义1->[ customize1 ]
[4]使用自定义2->[ customize2 ]
[d]设置---->[ DHCP ](默认)
[f]关注作者头条号
[q]退出(quit)\n''')
    if str(select_net) == '1':
        net_mode = "Intranet"
    elif str(select_net) == '2':
        net_mode = "Extranet"
    elif str(select_net) == '3':
        net_mode = "customize1"
    elif str(select_net) == '4':
        net_mode = "customize2"
    elif str(select_net) == 'q':
        exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
    elif str(select_net) == 'f':
        ff(url='https://www.toutiao.com/c/user/token/MS4wLjABAAAAhkfCgYOJBcLeeCmKBkqlgADR-D_woot1lAXGJFnkEnE/')
        exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
    else:
        net_mode = 'dhcp'
        dhcp_cmd = "netsh interface ipv4 set address name=\"" + net_name + "\" source=dhcp"
        system(dhcp_cmd)
        d = input('已启用[ DHCP ]模式,按任意键终止程序...')
        exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')
    files = input('请输入配置文件，默认[ ./connect.conf ]\n')
    if files:
        print('已输入[ %s ]' % files)
    else:
        files = './connect.conf'
        print('未输入,已使用默认值[ %s ]' % files)

    get_config(file=files, card_name=net_name, mode=net_mode, ip_list=ip_list, ip_info=network_info)


def get_NetworkManager():
    up = configparser.ConfigParser()
    network_config = '/etc/NetworkManager/NetworkManager.conf'
    up.read(network_config, encoding='utf8')
    if up.get('ifupdown', 'managed') == 'true':
        ii = '已开启NetworkManager管理'
        print(ii)
        logger.info(ii)
    else:
        mode = ('检测到本机未使用NetworkManager接管网络设备,是否立即开启(建议开启)\n请选择[ y/n ],默认 [ y ]')
        if str(mode):
            if str(mode) == 'n':
                exit('感谢使用')
            else:
                mode = 'y'
        else:
            mode = 'y'
        if str(mode) == 'y':
            bak_file = network_config + '.bak'
            if path.isfile(bak_file):
                print('已有备份[ %s ]' % bak_file)
            else:
                copyfile(network_config, bak_file)
            # if not path.isfile('/usr/bin/crudini'):

            cc = "crudini --set " + network_config + " ifupdown " + " managed " + " true"
            system(cc)

# if __name__ == 'main':
    '''
    获取系统类型
    '''
os_ver = platform.system()
print('检测到当前系统类型:[ %s ]' %os_ver)
if os_ver == 'Linux':
    ii = ('开始进入程序...')
    logger.info(ii)
else:
    exit('当前脚本不支持Linux系统，请访问下列网址获取Windows版本\n[ https://gitee.com/faith01238/IP/releases/ ]')

exit('By:  坐公交也用券@(今日头条,CSDN,博客园)')